package com.shareppy.nomrnaui;

import java.lang.reflect.Field;

import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;

import com.shareppy.nomrnaui.annotations.Layout;
import com.shareppy.nomrnaui.annotations.View;
import com.shareppy.nomrnaui.exception.MissingLayoutException;
import com.shareppy.nomrnaui.util.UIUtil;

public class NormanActivity extends Activity {

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		com.shareppy.nomrnaui.annotations.Menu menuAnnotation = getClass()
				.getAnnotation(com.shareppy.nomrnaui.annotations.Menu.class);
		if (menuAnnotation == null) {
			return false;
		}
		getMenuInflater().inflate(menuAnnotation.value(), menu);
		return true;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		configureLayout();
		cacheFields(savedInstanceState);
		on_create(savedInstanceState);
	}

	private void configureLayout() {
		Layout layoutAnnotation = getClass().getAnnotation(Layout.class);
		if (layoutAnnotation == null) {
			throw new MissingLayoutException(
					"Class must annotated with @Layout");
		}
		setActionBarTitle(layoutAnnotation.title());
		setActionBarSubTitle(layoutAnnotation.subtitle());
		setContentView(layoutAnnotation.value());
	}

	public void setActionBarTitle(int title) {
		if (title != 0) {
			getActionBar().setTitle(title);
		}
	}

	public void setActionBarTitle(String title) {
		if (title != null) {
			getActionBar().setTitle(title);
		}
	}

	public void setActionBarSubTitle(int subtitle) {
		if (subtitle != 0) {
			getActionBar().setSubtitle(subtitle);
		}
	}

	public void setActionBarSubTitle(String subtitle) {
		if (subtitle != null) {
			getActionBar().setSubtitle(subtitle);
		}
	}

	protected Activity getActivity() {
		return this;
	}

	private void cacheFields(Bundle savedInstanceState) {
		Field[] declaredFields = getClass().getDeclaredFields();
		for (Field field : declaredFields) {
			View annotation = field.getAnnotation(View.class);
			if (annotation != null) {
				field.setAccessible(true);
				try {
					android.view.View view = UIUtil.getView(getActivity(),
							annotation.value());
					// System.out.println(view);
					field.set(getActivity(), view);
				} catch (IllegalAccessException e) {
					e.printStackTrace();
				} catch (IllegalArgumentException e) {
					e.printStackTrace();
				}
			}
		}
	}

	protected void on_create(Bundle savedInstanceState) {
		return;
	}
}